import dynamic from 'dva/dynamic';
import {listRouteData} from '@/services/system/menu'
import {history} from "@@/core/history";


/**
 * 路由实体
 */
interface RouteProps {
  path: string,
  name: string,
  icon?: string,
  component?: string,
  authority?: string[],  // 根据localStorage的值，过滤菜单，只能控制到菜单，颗粒度太大，废弃
  permission?: PermissionProps[],
  routes?: RouteProps[],
}

/**
 * 权限实体
 */
interface PermissionProps {
  name: string,
  key: string,
}

/**
 * 路由数组
 */
let routeArray: RouteProps[] = [];

/**
 * 解析路由
 *
 * @param authRouteArray
 */
const parseRoutes = (authRouteArray: any) => {
  return (authRouteArray || []).map((item: any) => {
    if (item.routes && item.routes.length > 0) {
      return {
        path: item.path,
        name: item.name,
        icon: item.icon,
        authority: item.authority,
        routes: parseRoutes(item.routes),
      };
    }
    return {
      path: item.path,
      name: item.name,
      icon: item.icon,
      authority: item.authority,
      permission: item.permission,
      component: dynamic({component: () => import(`@/pages${item.component}/index.tsx`)}),
    };
  });
}

/**
 * 动态修改路由
 *
 * @param routes
 */
export function patchRoutes({routes}: any) {
  // console.log(routes)
  const curRouteArray = routes[0].routes[1].routes;
  curRouteArray.length = 0;
  // 添加首页
  curRouteArray.push({
    name: 'home',
    icon: 'home',
    path: '/home',
    component: dynamic({component: () => import(`@/pages/home`)}),
  });
  parseRoutes(routeArray).forEach((item: any) => {
    curRouteArray.push(item);
  });
  curRouteArray.push({
    path: '/',
    redirect: '/home',
  });
  curRouteArray.push({
    component: dynamic({component: () => import(`@/pages/exception/404`)}),
  });
  // console.log(curRouteArray);
}

/**
 * 该方法会在patchRoutes之前进行执行。
 * @param oldRender
 */
export function render(oldRender: any) {

  // 获取路由
  const {pathname} = history.location;
  if (pathname !== '/user/login') {
    // console.log(pathname)
    listRouteData().then((data: any) => {
      // console.log(data)
      routeArray = data?.data || [];
      oldRender();
    })
    // todo
  }else {
    oldRender();
  }
}
